package com.it.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.it.reggie.common.Result;
import com.it.reggie.entity.Category;
import com.it.reggie.entity.Dish;
import com.it.reggie.dto.DishDto;
import com.it.reggie.entity.DishFlavor;
import com.it.reggie.service.ICategoryService;
import com.it.reggie.service.IDishFlavorService;
import com.it.reggie.service.IDishService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author:cyh
 * @data:2022/12/15 19:31
 */
@Api(tags = "菜品管理")
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    IDishService dishService;

    @Autowired
    ICategoryService categoryService;

    @Autowired
    IDishFlavorService dishFlavorService;

    @Autowired
    RedisTemplate redisTemplate;

    @ApiOperation("分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "页码",required = true),
            @ApiImplicitParam(name = "pageSize",value = "每页记录数",required = true),
            @ApiImplicitParam(name = "name",value = "套餐名称",required = false)
    })
    @GetMapping("/page")
    public Result<Page> queryByPage(Integer page, Integer pageSize, String name){
        //创建page对象，设置当前页和每页大小
        Page<Dish> dishPage = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        List<DishDto> dishDtos = new ArrayList<>();
        // 封装查询条件 where name like '%%'
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name!=null&&name!="", Dish::getName, name);
        //调用page方法查询数据
        dishPage = dishService.page(dishPage, wrapper);
        //将所有的数据拷贝到dishDto中,再存入集合
        for (Dish dish : dishPage.getRecords()) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish,dishDto);
            //通过category_id查询categoryName存入dishdto中
            Category category =categoryService.getById(dish.getCategoryId());
            if (category!=null) {
                dishDto.setCategoryName(category.getName());
            }
            dishDtos.add(dishDto);
        }
        //将dishDtos集合的数据和dishPage中查询到的总条数封装到page里面
        dishDtoPage.setRecords(dishDtos);
        dishDtoPage.setTotal(dishPage.getTotal());
        return Result.success(dishDtoPage);
    }

    @PostMapping
    public Result save(@RequestBody DishDto dishDto){
        dishService.saveDishWithFlavor(dishDto);
        //清理当前添加菜品分类下的缓存
        String key="dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return Result.success(null);
    }

    //查询信息用于数据回显
    @GetMapping("/{id}")
    public Result<DishDto> queryById(@PathVariable Long id){
        DishDto dishDto=dishService.queryById(id);
        return Result.success(dishDto);
    }

    @PutMapping
    public Result update(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);
        //清除所有分类的菜品缓存
        Set keys=redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return Result.success(null);
    }

    @DeleteMapping
    public Result remove(@RequestParam("ids") List<Long> ids){
        dishService.removeByIds(ids);
        return Result.success(null);
    }

    @PostMapping("/status/{status}")
    public Result statusBatch(@PathVariable Integer status,@RequestParam("ids") List<Long> ids){
        LambdaUpdateWrapper<Dish> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(Dish::getStatus, status);
        wrapper.in(Dish::getId, ids);
        dishService.update(wrapper);

        return Result.success(null);
    }

    //根据分类id查询该分类下的所有菜品集合
    @GetMapping("/list")
    public Result<List<DishDto>> queryCategories(Long categoryId,Integer status){
        List<DishDto> dishDtoList=null;
        //动态构造key
        String key="dish_"+categoryId+"_"+status;
        //先从redis中获取缓存数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtoList!=null){
            //如果存在,直接返回,无需查讯数据库
            return Result.success(dishDtoList);
        }

        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(categoryId!=null,Dish::getCategoryId, categoryId);
        wrapper.eq(status!=null,Dish::getStatus, status);
        //查询该分类所有菜品信息
        List<Dish> dishList = dishService.list(wrapper);
        List<DishDto> dishDtos = new ArrayList<>();
        for (Dish dish : dishList) {
            DishDto dishDto = new DishDto();
            //将菜品信息封装到dishDto中
            BeanUtils.copyProperties(dish, dishDto);
            //根据id查询分类对象
            Category category = categoryService.getById(dish.getCategoryId());

            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            //根据菜品id查询口味哦信息,并封装到dishdto中
            LambdaQueryWrapper<DishFlavor> flavorWrapper = new LambdaQueryWrapper<>();
            flavorWrapper.eq(dish!=null,DishFlavor::getDishId,dish.getId());
            List<DishFlavor> flavors = dishFlavorService.list(flavorWrapper);
            dishDto.setFlavors(flavors);
            dishDtos.add(dishDto);
        }
        //查询到的菜品数据缓存到Redis
        redisTemplate.opsForValue().set(key, dishDtos, 60, TimeUnit.MINUTES);
        return Result.success(dishDtos);
    }


}
